import Cesium from '../Ces/Cesium';
import './Popup.css';

interface PopupOptions {
  callback?: () => void;
}

interface EarthPin {
  content: string;
}

class Popup {
  private _callback: (() => void) | undefined;
  private _target: HTMLElement | undefined;

  constructor(options: PopupOptions = {}) {
    if (!Cesium.defined(options)) {
      options = {};
    }
    this._callback = options.callback;
  }

  get target(): HTMLElement | undefined {
    return this._target;
  }

  set content(value: string) {
    if (Cesium.defined(this.target)) {
      const firstChild : any = this._target.firstChild
      firstChild.firstChild.innerHTML = value;
    }
  }

  createGraph(container: HTMLElement | undefined, earthPin: EarthPin | undefined): HTMLElement {
    this._target = Popup.createWrapNode(this._callback);
    if (Cesium.defined(container)) {
      container.appendChild(this._target);
    }
    if (Cesium.defined(earthPin)) {
      this.content = earthPin.content;
    }
    return this._target;
  }

  static createWrapNode(xcallback: (() => void) | undefined): HTMLElement {
    const targetDiv = document.createElement('div');
    targetDiv.className = 'common-popup';

    const contentWrapper = document.createElement('div');
    contentWrapper.className = 'popup-content-wrapper';

    const contentNode = document.createElement('div');
    contentNode.className = 'popup-content';
    contentWrapper.appendChild(contentNode);

    const tipContainer = document.createElement('div');
    tipContainer.className = 'popup-tip-wrapper';

    const tip = document.createElement('div');
    tip.className = 'popup-tip';
    tipContainer.appendChild(tip);

    const close = document.createElement('a');
    close.className = 'popup-close-button';
    close.innerText = '×';

    targetDiv.appendChild(contentWrapper);
    targetDiv.appendChild(tipContainer);

    if (Cesium.defined(xcallback)) {
      targetDiv.appendChild(close);
      close.addEventListener('click', () => {
        xcallback();
      });
    }

    return targetDiv;
  }

  isDestroyed(): boolean {
    return false;
  }

  destroy(): void {
    if (Cesium.defined(this._target)) {
      this._target.remove();
    }
    return Cesium.destroyObject(this);
  }
}

export default Popup;
